﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using Microsoft.Win32;
using System.IO.Pipes;
using System.Diagnostics;
using System.Runtime.InteropServices;


namespace RedFlag
{
    
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            string launchProg=null;
            string launchArgs = String.Empty;
            bool ProcessArrays=false;
            int StackLength=5;
            int ObjectDepth=4;
            string setBreakpoint = String.Empty;
            string pipeName=String.Empty;
            string notificationArg="/ServerName:";
           // System.Threading.Thread.Sleep(20000);
            if (args.Length >1 && args[0].StartsWith(notificationArg,StringComparison.OrdinalIgnoreCase))
            {
                // if the program is started with Notify (redflag.exe /Notify:RedFlag<n> <valid vile name>)
                // we are in IFEO mode - basically a parent RedFlag has set the Image File Execution Options
                // so we notify RedFlag to launch a process and delete the IFEO key.
                // construct a prog and arguments
                launchProg = args[1].Trim('\"');
                if (args.Length > 2)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int aCount = 2; aCount < args.Length; aCount++)
                    {
                        sb.Append(args[aCount]);
                        sb.Append(" ");
                    }
                    launchArgs = sb.ToString();
                }
                try
                {
                    string keyName = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\" + System.IO.Path.GetFileName(launchProg);
                    RegistryKey keyVal = Registry.LocalMachine.OpenSubKey(keyName, true);
                    keyVal.DeleteValue("Debugger", false);
                }
                catch {
                    // do not do anything if we cannot delete the key
                    return;
                }
                //Create NamedPipeServerStream
                //Wait for client to connect
                //Launch debugger
                //While connected, serialize exceptions
                return;
            }
                foreach (string arg in args)
                {
                    if (arg.ToUpper().StartsWith("/LAUNCH:")) launchProg = arg.Substring(8).Trim('\"');
                    if (arg.ToUpper().StartsWith("/ARGUMENTS:")) launchArgs = arg.Substring(11).Trim('\"');
                    if (arg.ToUpper().StartsWith("/OBJECTDEPTH:")) ObjectDepth = Convert.ToInt32(arg.Substring(13).Trim('\"'));
                    if (arg.ToUpper().StartsWith("/STACKLENGTH:")) StackLength = Convert.ToInt32(arg.Substring(13).Trim('\"'));
                    if (arg.ToUpper().StartsWith("/BREAKPOINT:")) setBreakpoint = arg.Substring(12).Trim('\'');
                    if (arg.ToUpper() == "/PROCESSARRAYS") ProcessArrays = true;
                }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (launchProg==null) Application.Run(new Form1(ProcessArrays,StackLength,ObjectDepth,setBreakpoint));
            else Application.Run(new Form1(launchProg, launchArgs, ProcessArrays, StackLength, ObjectDepth,setBreakpoint));
        }
        /// <summary>
        /// Copy the whole list in this case as text
        /// </summary>
        /// <param name="lb"></param>
        public static void CopyListBoxToClipboard(ListBox lb)
        {
            StringBuilder buffer = new StringBuilder();

            for (int i = 0; i < lb.Items.Count; i++)
            {
                buffer.Append(lb.Items[i].ToString());
                buffer.Append("\r\n");
            }

            Clipboard.SetText(buffer.ToString());
        }
        /// <summary>
        /// The LV is mighty large--copy only the selected item
        /// </summary>
        /// <param name="lb"></param>
        public static void CopyListViewToClipboard(ListView lv)
        {
            StringBuilder buffer = new StringBuilder();
            ListView.SelectedListViewItemCollection coll = lv.SelectedItems;
            foreach (ListViewItem item in coll)
            {
                foreach (System.Windows.Forms.ListViewItem.ListViewSubItem subItem in item.SubItems)
                {
                    buffer.Append(subItem.Text+"\t");
                }
                buffer.Append("\r\n");

            }
            Clipboard.SetText(buffer.ToString());
        }
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool CreateProcess(
           string lpApplicationName,
           string lpCommandLine,
           ref Microsoft.Samples.Debugging.CorDebug.NativeApi.SECURITY_ATTRIBUTES lpProcessAttributes,
           ref Microsoft.Samples.Debugging.CorDebug.NativeApi.SECURITY_ATTRIBUTES lpThreadAttributes,
           bool bInheritHandles,
           uint dwCreationFlags,
           IntPtr lpEnvironment,
           string lpCurrentDirectory,
           [In] ref Microsoft.Samples.Debugging.CorDebug.NativeApi.STARTUPINFO lpStartupInfo,
           out Microsoft.Samples.Debugging.CorDebug.NativeApi.PROCESS_INFORMATION lpProcessInformation);
    }
}
